<?php

namespace app\parent\service;

use app\common\service\BaseService;
use app\lib\exception\BaseException;
use app\models\ContractModel;
use app\models\CourseModel;
use app\models\DictionaryModel;
use app\models\GradesDetailsListsModel;
use app\models\GradesDetailsModel;
use app\models\MyApprovalModel;
use app\models\MyComplaintSuggestionModel;
use app\models\MyNoticeModel;
use app\models\MyNoticeObjectModel;
use app\models\ParentInformationModel;
use app\models\StudentModel;
use app\models\StudentSubjectInfosClassModel;
use app\models\UserModel;
use think\Db;

class MyService extends BaseService
{
    /**
     * User: wufeng
     * Date: 2020/03/09.
     *
     * @return array
     */
    public function myClass()
    {
        try {
            $myClass = $where = [];
            $student_id = (new ParentInformationModel())->get(parent_get_current_user_id())['student_id'];
            $campus_id = (new StudentModel())->get($student_id)['campus_id'];
            $where['student_id'] = $student_id;
            $where['campus_id'] = $campus_id;
            $class_subject_ids = (new StudentSubjectInfosClassModel())->where($where)->column('class_subject_id');
            $myClass['id'] = ['in', implode(',', array_unique($class_subject_ids))];
            $myClass['campus_id'] = $campus_id;
            $this->data['attending_classes'] = (new GradesDetailsModel())
                ->where($myClass)
                ->where(['graduation_status' => 0])
                ->select()
                ->toArray();
            foreach ($this->data['attending_classes'] as &$attending_class) {
                $attending_class['course_type'] = CourseModel::get(['id' => $attending_class['course_id']])['course_type'];
                $attending_class['course_type_text'] = DictionaryModel::get(['id' => $attending_class['course_type']])['name'];
                $res = (new ContractModel())->where(['student_id' => $student_id])->order('signing_date asc')->find();
                $attending_class['sign_up_date'] = $res['signing_date'];
                $attending_class['already_grades_class'] = $attending_class['already_arranged'].'/'.($attending_class['already_class'] - $attending_class['already_arranged']);
                $attending_class['total'] = (new ContractModel())->where(['student_id' => $student_id])->sum('balance') / 100;
                $attending_class['room'] = (implode('|', array_unique(explode(',', $attending_class['room_text']))));
            }

            $this->data['past_class'] = (new GradesDetailsModel())
                ->where($myClass)
                ->where(['graduation_status' => 1])
                ->select()
                ->toArray();
            foreach ($this->data['past_class'] as &$past_class) {
                $past_class['course_type'] = CourseModel::get(['id' => $past_class['course_id']])['course_type'];
                $past_class['course_type_text'] = DictionaryModel::get(['id' => $past_class['course_type']])['name'];
                $res = (new ContractModel())->where(['student_id' => $student_id])->order('signing_date asc')->find();
                $past_class['sign_up_date'] = $res['signing_date'];
                $past_class['already_grades_class'] = $past_class['already_arranged'].'/'.($past_class['already_class'] - $past_class['already_arranged']);
                $past_class['total'] = (new ContractModel())->where(['student_id' => $student_id])->sum('balance') / 100;
                $past_class['room'] = (implode('|', array_unique(explode(',', $past_class['room_text']))));
            }

            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, '');
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/09.
     *
     * @param $params
     *
     * @return array
     */
    public function attendanceRecord($params)
    {
        try {
            $where = [];
            $student_id = (new ParentInformationModel())->get(parent_get_current_user_id())['student_id'];
            $campus_id = (new StudentModel())->get($student_id)['campus_id'];
            $where['student_id'] = $student_id;
            $where['campus_id'] = $campus_id;
            $this->data = (new StudentSubjectInfosClassModel())
                ->where($where)
                ->order('class_date asc')
                ->select()
                ->toArray();
            $i = 0;
            foreach ($this->data as &$datum) {
                $i = $i + 1;
                $datum['class_day'] = '第'.$i.'节';
                $gradesDetailsLists = (new GradesDetailsListsModel())->get($datum['class_manage_details_id']);
                $datum['headmaster'] = $gradesDetailsLists['headmaster'];
                $datum['teacher'] = $gradesDetailsLists['teacher'];
                $datum['assistant'] = $gradesDetailsLists['assistant'];
                $datum['class_subject_start'] = $gradesDetailsLists['class_subject_start'];
                $datum['class_subject_end'] = $gradesDetailsLists['class_subject_end'];
                $datum['course_name'] = (new CourseModel())->get($datum['course_id'])['course_name'];
            }
            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/10.
     *
     * @param $params
     *
     * @return array
     */
    public function myLeave($params)
    {
        try {
            $where = [];
            $student_id = (new ParentInformationModel())->get(parent_get_current_user_id())['student_id'];
            $where['campus_id'] = (new StudentModel())->get($student_id)['campus_id'];
            $class_subject_ids = (new StudentSubjectInfosClassModel())->where(['student_id' => $student_id, 'campus_id' => $where['campus_id']])->column('class_subject_id');
            $where['id'] = ['in', implode(',', array_unique($class_subject_ids))];
            $where['graduation_status'] = 0;
            $this->data['lists'] = (new GradesDetailsModel())
                ->where($where)
                ->order('id desc')
                ->select()
                ->toArray();
            foreach ($this->data['lists'] as &$comment) {
                //班课类型
                $comment['course_type'] = CourseModel::get(['id' => $comment['course_id']])['course_type'];
                $comment['course_type_text'] = DictionaryModel::get(['id' => $comment['course_type']])['name'];
                $comment['gradesDetailsLists'] = (new StudentSubjectInfosClassModel())
                    ->where(['class_subject_id' => $comment['id'], 'student_id' => $student_id])
                    ->select()
                    ->toArray();
                $i = 0;
                foreach ($comment['gradesDetailsLists'] as &$list) {
                    $i = $i + 1;
                    $list['class_day'] = '第'.$i.'节';
                    $gradesDetailsLists = (new GradesDetailsListsModel())->get($list['class_manage_details_id']);
                    $list['class_datetime'] = $gradesDetailsLists['class_date'].' '.$gradesDetailsLists['class_subject_start'].'-'.$gradesDetailsLists['class_subject_end'];
                    $status_m = (new MyApprovalModel())->get(['cmdl_id' => $list['class_manage_details_id'], 'user_id' => parent_get_current_user_id()])['status'];
                    $list['approval_status'] = $status_m ? $status_m : 0;
                }
            }

            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/07.
     *
     * @param $params
     *
     * @return array
     */
    public function launchApproval($params)
    {
        try {
            $data = [];
            $data['approval_time'] = date('Y-m-d H:i:s'); //审批时间
            $data['user_id'] = parent_get_current_user_id(); //发布人id
            $data['cmdl_id'] = $params['cmdl_id']; //审批名称
            $data['approval_name'] = $params['approval_name']; //审批名称
            $data['content'] = $params['content']; //具体内容
            $data['picture'] = $params['picture']; //图片
            $data['approver'] = $params['approver']; //审批人
            $data['status'] = 1;
            $data['type'] = $params['type'];
            Db::name('edu_my_approval')->insert($data);
            $id = Db::name('edu_my_approval')->getLastInsID();
            $student_id = (new ParentInformationModel())->get(parent_get_current_user_id())['student_id'];
            Db::name('edu_class_subject_student_infos')->where(['class_manage_details_id' => $params['cmdl_id'], 'student_id' => $student_id])->update(['is_submit' => 1]);

            $_data = [];
            $approver_ids = explode(',', $params['approver']);
            foreach ($approver_ids as &$approver_id) {
                $_data['approval_id'] = $id;
                $_data['approver_id'] = $approver_id;
                $_data['status'] = 1;
                Db::name('edu_my_approval_relation')->insert($_data);
            }

			//写入通知记录
			$notice = [];
			$notice['notice_time'] = date('Y-m-d H:i:s'); //通知时间
			$notice['user_id'] = xcxapi_get_current_user_id(); //操作审批人的id
			$notice['notice_object'] = $params['approver']; //通知对象
			$notice['notice_name'] = $params['approval_name']; //通知名称
			$notice['content'] = '收到了'.parent_get_current_name().$params['approval_name'].'审批申请'; //具体内容
			$notice['notice_type'] = 1; //通知方向：1机构端、家长端；2机构端；3家长端
			$notice['status'] = 1; //存稿还是发布：1发布 2存稿

			Db::name('edu_my_notice')->insert($notice);  //插入通知表
			$notice_id = Db::name('edu_my_notice')->getLastInsID();
			$notice_data = [];
			$notices = explode(',', $notice['notice_object']);
			foreach ($notices as &$notice) {
				$arr = [];
				$arr['notice_id'] = $notice_id;
				$arr['notice_object_id'] = $notice;
				$arr['n_type'] = 2;
				$arr['notice_type'] = 1;
				$notice_data[] = $arr;
			}
			Db::name('edu_my_notice_object')->insertAll($notice_data);
		
		} catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/09.
     *
     * @param $params
     *
     * @return array
     */
    public function paymentRecord($params)
    {
        try {
            $where = [];
            $where['user_id'] = xcxapi_get_current_user_id();
            $where['status'] = $params['status']; //存稿还是发布：1发布 2存稿
            $this->data['notice'] = (new MyNoticeModel())
                ->where($where)
                ->select()
                ->toArray();

            foreach ($this->data['notice'] as &$val) {
                $val['name'] = (new UserModel())->get($val['user_id'])['name'];
            }
            $this->data['draft_num'] = (new MyNoticeModel())
                ->where(['user_id' => xcxapi_get_current_user_id(), 'status' => 2])
                ->count();
            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/09.
     *
     * @param $params
     *
     * @return array
     */
    public function complaintSuggestion($params)
    {
        try {
            $data = [];
            $data['create_time'] = date('Y-m-d H:i:s'); //作业时间
            $data['user_id'] = parent_get_current_user_id(); //发布人
            $data['content'] = $params['content']; //具体内容
            $data['audio'] = $params['audio']; //音频
            $data['audio_duration'] = $params['audio_duration']; //音频时长
            $data['video'] = $params['video']; //视频
            $data['picture'] = $params['picture']; //图片
            (new MyComplaintSuggestionModel())->save($data);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/12.
     *
     * @param $params
     *
     * @return array
     */
    public function information($params)
    {
        try {
            $this->data['systemNoticeList'] = (new MyNoticeObjectModel())
                ->where(['notice_object_id' => parent_get_current_user_id()])
				->order('id desc')
                ->select()
                ->toArray();
			$is_unread_count = 0;
            foreach ($this->data['systemNoticeList'] as &$val) {
                $myNotice = (new MyNoticeModel())->get($val['notice_id']);
                $val['notice_name'] = $myNotice['notice_name'];
                $val['notice_time'] = $myNotice['notice_time'];
                $val['user_id'] = $myNotice['user_id'];
                $val['user_name'] = (new UserModel())->get($myNotice['user_id'])['name'];
                $val['content'] = $myNotice['content'];
                $val['audio'] = $myNotice['audio'];
                $val['audio_duration'] = $myNotice['audio_duration'];
                $val['video'] = $myNotice['video'];
                $val['picture'] = explode(',', $myNotice['picture']) ? explode(',', $myNotice['picture']) : [];
				$val['s_notice_type'] = $val['notice_type'];
                $val['status'] = $myNotice['status'];
				if($val['is_read'] == 0){ //未读
					$is_unread_count = $is_unread_count + 1;
				}
					
            }
			$this->data['systemNoticeUnReadCount'] = $is_unread_count;
            if (empty($this->data)) {
                /*throw new BaseException('NO_DATA');*/
            }
			
			
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * User: wufeng
     * Date: 2020/03/14.
     *
     * @param $params
     *
     * @return array
     */
    public function isRead($params)
    {
        try {
            (new MyNoticeObjectModel())->save(['is_read' => 1], ['id' => $params['id']]);
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

	/**
	 * User: wufeng
	 * Date: 2020/03/30
	 *
	 * @param $params
	 * @return array
	 */
	public function uploadHead($params)
	{
		try {
			(new ParentInformationModel())->save(['img' => $params['img']], ['id' => $params['id']]);
		} catch (\Exception $e) {
			$this->errorMessage($e, $params);
		}

		return $this->return;
	}
}
